package com.niodata.dp.task.dao.handler;

import com.niodata.dp.log.LogUtil;
import com.niodata.dp.mybatis.DpMybatisTypeHandler;
import com.niodata.dp.task.entity.TaskAlertSetting;
import com.niodata.dp.util.JsonUtil;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.log4j.Logger;


public class TaskAlertSettingTypeHandler extends BaseTypeHandler<TaskAlertSetting>
    implements DpMybatisTypeHandler {

  private static final Logger logger = Logger.getLogger(TaskAlertSettingTypeHandler.class);

  @Override
  public JdbcType getJdbcType() {
    return JdbcType.LONGVARCHAR;
  }

  @Override
  public Class getTypeHandlerClass() {
    return TaskAlertSettingTypeHandler.class;
  }

  @Override
  public Class getJavaClass() {
    return TaskAlertSetting.class;
  }

  @Override
  public void setNonNullParameter(
      PreparedStatement ps, int i, TaskAlertSetting parameter, JdbcType jdbcType)
      throws SQLException {
    try {
      String json = JsonUtil.toJson(parameter);
      ps.setString(i, json);
    } catch (IOException e) {
      LogUtil.logStackTrace(logger, e);
    }
  }

  @Override
  public TaskAlertSetting getNullableResult(ResultSet rs, String columnName) throws SQLException {
    String json = rs.getString(columnName);
    if (json != null && json.length() > 0) {
      try {
        return JsonUtil.fromJson(TaskAlertSetting.class, json);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return null;
  }

  @Override
  public TaskAlertSetting getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String json = rs.getString(columnIndex);
    if (json != null && json.length() > 0) {
      try {
        return JsonUtil.fromJson(TaskAlertSetting.class, json);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return null;
  }

  @Override
  public TaskAlertSetting getNullableResult(CallableStatement cs, int columnIndex)
      throws SQLException {
    return null;
  }
}
